﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Text.Encodings.Web;
using SnakeShop.Model.ViewModels.UI;

namespace SnakeShop.Auth.Policys
{
    public class ApiResponseForAdminHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {

        public ApiResponseForAdminHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory log,
            UrlEncoder en
            , ISystemClock clock) : base(options, log, en, clock)
        {

        }


        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            //todo 异步授权？？
            
            throw new NotImplementedException();
        }

        protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            Response.ContentType = "application/json";

            //todo 放开会怎么样？
            //Response.StatusCode = StatusCodes.Status401Unauthorized;
            //await Response.WriteAsync(JsonConvert.SerializeObject(new ApiResponse(StatusCode.CODE_401)));

            var jm = new AdminUiCallBack();
            jm.code = 401;
            jm.data = 401;
            jm.msg = "无权访问";
            await Response.WriteAsync(JsonConvert.SerializeObject(jm));
        }

        protected override async Task HandleForbiddenAsync(AuthenticationProperties properties)
        {

            Response.ContentType = "application/json";
            //Response.StatusCode = StatusCodes.Status403Forbidden;
            //await Response.WriteAsync(JsonConvert.SerializeObject(new ApiResponse(StatusCode.CODE403)));

            var jm = new AdminUiCallBack();
            jm.code = 403;
            jm.msg = "很抱歉，您的访问权限等级不够，联系管理员!!";
            await Response.WriteAsync(JsonConvert.SerializeObject(jm));
        }
    }
}
